package cn.iocoder.yudao.framework.base.common.reference;


import java.io.Serializable;

public class ExpireReference<T> implements Serializable {


    private T value;

    private long expireTime = Long.MAX_VALUE;
    private boolean expireMode;

    private ExpireReference( ) {

    }

    public boolean isExpire() {
        if (expireMode) {
            return ttl() <= 0;
        }
        return false;
    }

    public long ttl() {
        if (expireMode) {
            return expireTime - System.currentTimeMillis();
        }
        return -1L;

    }

    public T getValue() {
        if (isExpire()) {
            return null;
        }
        return value;
    }

    public static <T> ExpireReference build(T value, long expire) {

        ExpireReference<T> result = new ExpireReference<T>();
        result.value = value;
        result.expireTime = System.currentTimeMillis() + expire;
        result.expireMode = true;
        return result;
    }

    public static <T> ExpireReference build(T value) {

        ExpireReference<T> result = new ExpireReference<T>();
        result.value = value;

        return result;
    }

}